﻿<%@ WebHandler Language="C#" Class="YPContaienrHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.BusinessFactory;
using BusinessRule.IBusiness;
using DatabaseAccess.DBUtility;
/*Description: 批量检验处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:2021-12-27
'Rewriter:
'Rewrite Date:
*/
public class YPContaienrHandler : IHttpHandler, IRequiresSessionState
{
    string fileBasePath = "/InSiteWebApplication/Temp/叶片机加例外放行/";
    uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
    YPContainerBusiness ypContainerBusiness = new YPContainerBusiness();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "缓存过期，请重新登录", Result = false }));
                return;
            }
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetContainerNoList":
                    GetContainerNoList(context);
                    break;
                case "GetCheckPointDocFileList":
                    GetCheckPointDocFileList(context);
                    break;
                case "GetForgeContainerList"://获取锻件批次列表
                    GetForgeContainerList(context);
                    break;
                case "SaveYpMacheExtraWork": //保存例外放行数据（机加）
                    SaveYpMacheExtraWork(context);
                    break;
                case "GetMacheHoldContainerList"://获取机加暂停批次列表（平行作业工序暂停）
                    GetMacheHoldContainerList(context);
                    break;
                case "ReleaseMacheHoldContainer"://释放机加暂停批次（平行作业工序暂停）
                    ReleaseMacheHoldContainer(context);
                    break;
                case "UploadReleaseFile"://上传释放文件（平行作业工序暂停）
                    UploadReleaseFile(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 获取实测值附件列表
    /// </summary>
    /// <param name="context"></param>
    public void GetCheckPointDocFileList(HttpContext context)
    {
        string containerID = context.Request.Form["containerId"].ToString();
       string pageIndex = context.Request.Form["pageIndex"].ToString();
       string pageSize= context.Request.Form["pageSize"].ToString();
        string sql = @"SELECT w.workflowstepname,nvl(s.checkpointnotedis,s.checkpointnote) checkpointnote,
nvl(sp.workcheckpointresultnotedis,sp.workcheckpointresultnote) workcheckpointresultnote,
NVL(sp.checkpointresultnotedis,sp.checkpointresultnote) checkpointresultnote,
e.fullname workername,sp.workresultdocpath,sp.checkresultdocpath,'' workDocName,'' checkDocName
FROM stepcheckpointresult sp
LEFT JOIN stepcheckpoint s ON s.stepcheckpointid = sp.stepcheckpointid
LEFT JOIN Workflowstep w ON w.workflowstepid = s.workflowstepid
LEFT JOIN employee e ON e.employeeid = sp.workerid
WHERE sp.containerid = '" + containerID + "' AND sp.workresultdocpath IS NOT NULL";
        uMESPagingDataDTO paraPage =new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageIndex);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        string url = "http://" + context.Request.Url.Host + context.Request.ApplicationPath;
        foreach (DataRow item in result.DBTable.Rows)
        {
            item["workDocName"] = Path.GetFileName(item["workresultdocpath"].ToString());
            item["workresultdocpath"] = url + item["workresultdocpath"].ToString();
            if (!string.IsNullOrWhiteSpace(item["checkresultdocpath"].ToString()))
            {
                item["checkDocName"] = Path.GetFileName(item["checkresultdocpath"].ToString());
                item["checkresultdocpath"] = url + item["checkresultdocpath"].ToString();
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取已经检验首件批次号以及当前批次子序号
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerNoList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductId", context.Request.Form["productId"].ToString());
        para.Add("ContainerId", context.Request.Form["containerId"].ToString());
        para.Add("WorkFlowStepId", context.Request.Form["workFlowStepId"].ToString());
        para.Add("CurrUserId", m_UserInfo.EmployeeID.ToString());
        DataSet ds = ypContainerBusiness.GetFirstContainerNOInfo(para);
        DataTable newdt = m_Common.GetContainerInfoByPerContianerID(para["ContainerId"]);
        DataTable newdt_ = m_Common.GetContainerStepWorkReportChildInfo(para["ContainerId"]);
        foreach (DataRow r_ in newdt_.Rows)
        {
            foreach (DataRow r in newdt.Rows)
            {
                if (r_["CHILDCONTAINERID"].ToString() == r["CONTAINERID"].ToString())
                {
                    r.Delete();
                    newdt.AcceptChanges();
                    break;
                }
            }
        }
        ds.Tables.Add(newdt);
        uMESProcessResult res = new uMESProcessResult() { DBDataSet = ds };
        context.Response.Write(JsonConvert.SerializeObject(res));
    }
    
    /// <summary>
    /// 获取锻件批次列表数据（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetForgeContainerList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("PageIndex", context.Request.Form["pageIndex"].ToString());
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());
        para.Add("ScanContainerName", context.Request.Form["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = m_Common.ContainerScan(para["ScanContainerName"].ToString());
        }
        para.Add("ContainerName", context.Request.Form["containerName"].ToString());
        uMESProcessResult res = ypContainerBusiness.GetForgeContainerListByPage(para);
        context.Response.Write(JsonConvert.SerializeObject(res));
    }
    /// <summary>
    /// 保存叶片机加平行作业工序
    /// </summary>
    /// <param name="context"></param>
    public void SaveYpMacheExtraWork(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        Dictionary<string, string> para = new Dictionary<string, string>();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["paramDt"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择批次" }));
            return;
        }
        para.Add("pxSpecNo", context.Request.Form["pxSpecNo"].ToString());
        para.Add("extraOddNum", context.Request.Form["extraOddNum"].ToString());
        uMESProcessResult res = ypContainerBusiness.SaveYpMacheExtraWork(dt, para);
        context.Response.Write(JsonConvert.SerializeObject(res));
    }
    /// <summary>
    /// 获取机加暂停批次（平行作业工序暂停）
    /// </summary>
    /// <param name="context"></param>
    public void GetMacheHoldContainerList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("PageIndex", context.Request.Form["pageIndex"].ToString());
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());
        para.Add("ScanContainerName", context.Request.Form["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = m_Common.ContainerScan(para["ScanContainerName"].ToString());
        }
        para.Add("ContainerName", context.Request.Form["containerName"].ToString());
        uMESProcessResult res = ypContainerBusiness.GetMacheHoldContainerList(para);
        context.Response.Write(JsonConvert.SerializeObject(res));
    }

    /// <summary>
    /// 释放机加暂停批次（平行作业工序暂停释放）
    /// </summary>
    /// <param name="context"></param>
    public void ReleaseMacheHoldContainer(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择批次数据" }));
            return;
        }
        uMESProcessResult result = ypContainerBusiness.ReleaseMacheHoldContainer(dt, m_UserInfo.EmployeeID.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 上传释放文件
    /// </summary>
    /// <param name="context"></param>
    public void UploadReleaseFile(HttpContext context)
    {
        string fpath = string.Empty;
        try
        {
            uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "上传成功" };
            string containerId = context.Request["containerId"].ToString();
            if (string.IsNullOrWhiteSpace(containerId))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未选择批次！", Result = false }));
                return;
            }
            if (!Directory.Exists(context.Server.MapPath(fileBasePath)))
            {
                Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            var files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
                return;
            }
            var file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string fileSuffix = Path.GetExtension(file.FileName);//文件后缀
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileSuffix;
            fpath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(fpath);//保存文件
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("parentId", containerId);
            dic.Add("fileName", fileName);
            dic.Add("filePath", fpath);
            //保存文件路径到数据库
            if (!m_Common.SaveObjectFileInfo(dic))
            {
                DeleteFile(fpath);//报错，则删除上传的文件
                result.Result = false;
                result.Message = "文件上传保存出错";
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        catch (Exception ex)
        {
            DeleteFile(fpath);//报错，则删除上传的文件
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "上传出错，原因：" + ex.Message, Result = false }));
        }
    }
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fpath">文件地址</param>
    private void DeleteFile(string fpath)
    {
        if (File.Exists(fpath))
        {
            new FileInfo(fpath).Attributes = FileAttributes.Normal;
            File.Delete(fpath);
        }
    }

}